class_name Cell
extends Node2D
signal ready_split(parent)

#export (SpriteFrames) var redFrames#team1
#export (SpriteFrames) var blueFrames#team0
#export (Texture) var redTex
#export (Texture) var blueTex

var frametouse
var textouse

enum CellState {
	Idle,
	Move,
	Die
}
var state = CellState.Idle
var listofenemyable = []
export var targetable = true;
export var team = 0
export var speed = 10
export var search_range = 30.0
export var attack_range = 60.0
const lifespan_max = 100.0#the max lifespan of a cell
export (float) var lifespan = 50.0#current lifespan
export var dying_scale = 1.0#the speed to die naturally
export var attack = 1
export var split_percentage = 0.6#when the lifespan/lifespan_max reached the percentage the cell might split
export var split_chance = 0.5#when able to split, the chance to split every tick
var target = null
var showinfo = false
var splitable = true

# Called when the node enters the scene tree for the first time.
func _ready():
	connect("ready_split", get_parent().get_parent().get_parent(), "split_cell")
	$Area2D/CollisionShape2D.shape.radius = search_range
	pass


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	
	if $AnimatedSprite.frame == $AnimatedSprite.frames.get_frame_count($AnimatedSprite.animation)-1 and state == CellState.Die:
		queue_free()
	match state:
		CellState.Die:
			$AnimatedSprite.animation="Die"
		CellState.Idle:
			$AnimatedSprite.animation="Move"
		CellState.Move:
			$AnimatedSprite.animation="Move"
	pass

func endinit():
	$AnimatedSprite.frames = frametouse
	
	$Sprite.texture = textouse


func update():
	#$Sprite.material.set_shader_param("team", team)
	var cost = speed / 100.0 + attack / 10.0 + search_range / 100.0
	lifespan -= float(cost) * dying_scale
	lifespan = clamp(lifespan,0,lifespan_max)
	if lifespan <= 0:
		targetable = false;
		state = CellState.Die
	else:
		targetable = true;
		state = CellState.Idle
	$Label.visible = false
	#if showinfo and is_instance_valid(target):
		#$Label.text =  str(team) + " looking for " + str(target.name) #+ "/" + str(lifespan_max) + " " + str(state)
	#else:
		#$Label.text =  str(name) + " " + str (team)
	if state != CellState.Die:
		for cell in listofenemyable:
			if is_instance_valid(target):
				if is_instance_valid(cell):
					if cell.filename == "res://Cell.tscn":
						if position.distance_to(target.position) > position.distance_to(cell.position) and cell.targetable:
							target = cell
					if cell.filename == "res://food.tscn" and lifespan < lifespan_max * split_percentage:
						if position.distance_to(target.position) > position.distance_to(cell.position):
							target = cell
			else:
				target = cell
		
		if is_instance_valid(target):
			if 	position.distance_to(target.position) < search_range:
				state = CellState.Move
			else:
				state = CellState.Idle
				
		else:
			state = CellState.Idle
	
	match state:
		CellState.Idle:
			Idle()
		CellState.Move:
			Move(target)
	
	if lifespan >= lifespan_max * split_percentage:
		randomize()
		if randf() < split_chance and splitable:
			emit_signal("ready_split", self)
		
func Move(Target):
	if position.distance_to(Target.position) > attack_range:
		position.x += speed * (position.direction_to(Target.position)).x
		position.x = clamp(position.x,50,974)
		position.y += speed * (position.direction_to(Target.position)).y
		position.y = clamp(position.y,50,550)
	else:
		if target.filename == "res://Cell.tscn":
			#print(self.name, " attack enemy!", target.name)
			if Target.targetable:
				Target.lifespan-=attack
				splitable = false
			if Target.lifespan <= 0 and Target.targetable:
				listofenemyable.erase(Target)
				#var prelife = lifespan
				#lifespan += 30
				splitable = true
				#print(self.name, " regained lifespan, from :", prelife, " to", lifespan)
		if target.filename == "res://food.tscn" and lifespan < lifespan_max * split_percentage:
			#var prelife = lifespan
			lifespan += 10 + randi()%10 - 5
			target.resource -= 1
			#print(self.name, "food eat, regained lifespan, from :", prelife, " to", lifespan)
func Idle():
	var direction = Vector2(randf()-0.5,randf()-0.5)
	direction = direction.normalized()
	position.x += speed * direction.x
	position.x = clamp(position.x,50,974)
	position.y += speed * direction.y
	position.y = clamp(position.y,50,550)
	state = CellState.Idle

#func _draw():
	#draw_arc(Vector2(0,0), search_range, 0, 2*PI, 16, Color.red)
	#if is_instance_valid(target):
		#if position.distance_to(target.position) < search_range:
			#draw_line(Vector2(0,0), target.position - position, Color.royalblue, 20)


func _on_Area2D_body_entered(body):
	var targetcell = body.get_parent()
	#print(targetcell.filename)
	if targetcell.filename == "res://Cell.tscn":
		if targetcell.team != team:
			#print(self.name, " find enemy!", targetcell.name)
			listofenemyable.push_back(targetcell)
			
	if targetcell.filename == "res://food.tscn":
		#print("add food!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
		listofenemyable.push_back(targetcell)
	pass # Replace with function body.




func _on_RigidBody2D_input_event(viewport, event, shape_idx):
	if event.is_pressed():
		showinfo = !showinfo
	pass # Replace with function body.
